﻿using LDC_Shop_B.Models;
using LDC_Shop_B.Models.Database;
using LDC_Shop_B.Serives;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace LDC_Shop_B.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly LDC_ShopBContext _db;
        private readonly IJWTService _jwtService;


        public UserController(LDC_ShopBContext db, IJWTService jwtService)
        {
            _db = db;
            _jwtService = jwtService;
        }


        //注册
        /// <summary>
        /// 用户使用手机号码，密码进行注册，密码需要二次确认
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Register(RegisterRequest request)
        {
            //密码需要二次确认
            if (request.Password != request.CirPassword)
                return "两次密码输入不一致";

            //随机数1000-9999
            var salt = new Random().Next(1000, 9999);

            //123456+随机值   “E1ADC3949BA59ABBE56E057F2F883E”  //结果变化
            //222222    "E1xxxxxxxxxxxxxxxxxxxxxxxxxxxx"   //所有的组合记录下来
            //在对密码进行MD5 md5(密码+随机数)

            var md5 = MD5Helper.MD5Encrypt32(request.Password + salt.ToString());

            //判断手机号码是否重复 拿这个手机号码 去数据库查 有没有存在
            if (_db.Users.Any(x => x.Mobile == request.Mobile))
                return "手机号码已存在";
            
            //把信息添加到数据库 注册成功
            _db.Users.Add(new User
            {
                CreateTime = DateTime.Now,
                Mobile = request.Mobile,
                Password = md5,
                NickName = string.Empty,
                Photo=string.Empty,
                Salt= salt.ToString()
            });
            //保存更改
            var row = _db.SaveChanges();
            if (row > 0)
                return "注册成功";
            return "注册失败";
        }

        //登录
        /// <summary>
        /// 用户使用手机号码，密码进行登录，登录后可访问需要授权的页面
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Login(LoginRequest request)
        {
            //1、使用手机号码去数据查询用户
            var user = _db.Users.FirstOrDefault(x => x.Mobile == request.Mobile);

            //2、判断是否空
            if(user == null)
                return "用户不存在";

            //生成md5字符串                      输入的         数据库的盐值
            var md5 = MD5Helper.MD5Encrypt32(request.Password + user.Salt.ToString());

            //3、判断密码是否正确md5  
            if(user.Password != md5)
                return "密码不正确";

            //4、创建token
            return _jwtService.CreateToken(user.UserId,user.Mobile);
        }

        //个人中心（需要查询用户各订单状态数量，用户头像，用户昵称（如果没有设置昵称用手机号码代替））
        [Authorize]
        [HttpPost]
        public GetUserInfoResponse GetUserInfo()
        {
            //通过登录用户信息 查询 用户相关 用户头像，用户昵称 

            //获取存储在 token 里用户信息
            var userId = Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value;
            //插叙用户对象
            var user = _db.Users.FirstOrDefault(x => x.UserId == Convert.ToInt32(userId));
            if (user == null)
                return null;

            //返回对象
            var response = new GetUserInfoResponse
            {
                NickName = user.NickName,
                Photo = user.Photo
            };
            //如果没有设置昵称用手机号码代替
            if (string.IsNullOrEmpty(response.NickName))
                response.NickName = user.Mobile;

            return response;
        }

        //修改用户信息（需要修改头像，用户昵称）
        [Authorize]
        [HttpPost]
        public string UpdateUserInfo(UpdateUserInfoRequest request)
        {
            //获取存储在 token 里用户信息
            var userId = Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value;
            //查询用户对象
            var user = _db.Users.FirstOrDefault(x => x.UserId == Convert.ToInt32(userId));
            if (user == null)
                return null;

            //赋值更新用户信息
            user.NickName = request.NickName;
            user.Photo = request.Photo;
            //更新用户对象
            _db.Users.Update(user);
            //提交到数据库
            var row = _db.SaveChanges();
            if (row > 0)
                return "成功";
            return "失败";
        }
    }
}
